# inc/config_manager.py 增强版
from datetime import datetime, timedelta
import pytz
import os
from flask import current_app, g
from .models import db, SystemConfig


class SystemConfigManager:
    _cache = None
    _last_update = None
    _cache_timeout = 300  # 5分钟缓存

    @classmethod
    def get_config(cls, refresh=False):
        """获取系统配置（带缓存机制）"""
        if refresh or cls._cache is None or \
                (cls._last_update and (datetime.now() - cls._last_update).total_seconds() > cls._cache_timeout):
            try:
                cls._cache = SystemConfig.query.first()
                if not cls._cache:
                    # 如果没有配置，创建默认配置
                    cls._cache = SystemConfig()
                    # 仅在模型包含 timezone 字段时设置它，避免模型/代码不一致导致异常
                    if hasattr(cls._cache, 'timezone'):
                        cls._cache.timezone = os.environ.get('DEFAULT_TIMEZONE', 'Asia/Shanghai')  # 默认时区
                    db.session.add(cls._cache)
                    db.session.commit()
                cls._last_update = datetime.now()
            except Exception as e:
                current_app.logger.error(f"加载系统配置失败: {str(e)}")
                # 如果数据库不可用，返回一个默认配置对象
                cls._cache = SystemConfig()
        return cls._cache

    @classmethod
    def get_value(cls, key, default=None):
        """直接获取配置值"""
        config = cls.get_config()
        return getattr(config, key, default)

    @classmethod
    def update_config(cls, **kwargs):
        """更新系统配置"""
        try:
            config = cls.get_config()
            for key, value in kwargs.items():
                if hasattr(config, key):
                    setattr(config, key, value)
            db.session.commit()
            # 更新缓存
            cls._cache = config
            cls._last_update = datetime.now()
            return True
        except Exception as e:
            current_app.logger.error(f"更新系统配置失败: {str(e)}")
            db.session.rollback()
            return False


# 保留原有函数以保持兼容性
def load_system_config():
    """加载系统配置到应用上下文和全局变量"""
    try:
        config = SystemConfigManager.get_config()

        # 存储到应用上下文
        g.system_config = config

        # 更新应用配置
        current_app.config.update({
            'SITE_NAME': config.site_name,
            'SITE_TITLE': config.site_title,
            'COMPANY_NAME': config.company_name,
            'CONTACT_EMAIL': config.contact_email,
            'FOOTER_INFO': config.footer_info,
            'OPERATION_LOG_ENABLED': config.operation_log_enabled,
            'BACKUP_ENABLED': config.backup_enabled,
            'BACKUP_SCHEDULE': config.backup_schedule,
            'BACKUP_RETENTION_COUNT': config.backup_retention_count,
        })

        return True
    except Exception as e:
        current_app.logger.error(f"加载系统配置失败: {str(e)}")
        return False